# -*- coding: utf-8 -*-
import socket
import time
import traceback
import os


class LogClient(object):
    """docstring for LogClient"""
    def __init__(self, port=None):
        super(LogClient, self).__init__()
        if port is None:
            port = 10909
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.addr = ('127.0.0.1', port)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.sock.close()

    def write(self, msg):
        if not isinstance(msg, bytes):
            msg = msg.encode('utf-8', 'ignore')
        send = self.sock.sendto(msg, self.addr)
        # print(send)

def print_log(msg, port=None):
    try:
        with LogClient(port) as lc:
            # print(msg, file=lc, end='')
            lc.write(msg)
    except Exception as e:
        traceback.print_exc()
        print(msg)

if __name__ == '__main__':
    for i in range(10):
        print(i)
        msg = 'log client msg\n msg [{0}]'.format(i)
        print_log(msg)
        time.sleep(1)

'''
class Test(object):
    def __init__(self):
        super(Test, self).__init__()
        print('print __init__')

    def __enter__(self):
        print('print __enter__')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('print __exit__')
'''